<!-- eslint-disable -->

<script lang="ts" setup>
import type {
  VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from 'vxe-table';

import { computed, onMounted, ref } from 'vue';

import { Button, Form, Input, message, Modal, Select } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  dealWithdrawApi,
  getWithdrawListApi,
  type WithdrawInfo,
} from '#/api/core/hhr';

// 添加分页相关的响应式变量
const currentPage = ref(1);
const totalPage = ref(1);

// 表格引用
const gridRef = ref<VxeGridInstance>();

// 存储表格数据
const tableData = ref<WithdrawInfo[]>([]);

// 状态选项
const statusOptions = [
  { label: '全部', value: -1 },
  { label: '待处理', value: 0 },
  { label: '已处理', value: 1 },
];

// 表格配置
const gridOptions = computed<VxeGridProps<WithdrawInfo>>(() => ({
  columns: [
    { field: 'id', title: 'ID', width: 80 },
    { field: 'username', title: '提现用户' },
    { field: 'alipay_account', title: '支付宝账号' },
    { field: 'alipay_name', title: '支付宝姓名' },
    { field: 'money', title: '提现金额' },
    { field: 'fee', title: '手续费' },
    { field: 'received_money', title: '实际到账金额' },
    {
      field: 'apply_status',
      title: '状态',
      width: 100,
    },
    {
      field: 'apply_time',
      title: '提交时间',
      width: 180,
    },
    {
      field: 'deal_time',
      title: '处理时间',
      width: 180,
    },
    { field: 'comment', title: '备注' },
    { field: 'detail', title: '详情', width: 100, slots: { default: 'detail' } },
    {
      title: '操作',
      width: 120,
      slots: {
        default: 'operate',
      },
    },
  ],
  data: tableData.value,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    total: totalPage.value * 10,
    currentPage: currentPage.value,
    layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total'],
    perfect: true,
  },
  sortConfig: {
    multiple: true,
  },
}));

// 修改 pageChange 事件处理器，添加类型
const gridEvents: VxeGridListeners<WithdrawInfo> = {
  pageChange: ({ currentPage: newPage }: { currentPage: number }) => {
    currentPage.value = newPage;
    loadData();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 定义搜索表单的数据结构
interface SearchForm {
  username: string;
  status: number;
}

// 搜索表单数据
const searchForm = ref<SearchForm>({
  username: '',
  status: -1,
});

// 处理提款相关
const dealModalVisible = ref(false);
const currentRow = ref<null | WithdrawInfo>(null);
const dealComment = ref('');

// 打开处理弹窗
function handleDeal(row: WithdrawInfo) {
  currentRow.value = row;
  dealComment.value = '';
  dealModalVisible.value = true;
}

// 确认处理
async function confirmDeal() {
  if (!currentRow.value) return;

  try {
    await dealWithdrawApi({
      id: currentRow.value.id,
      comment: dealComment.value,
    });
    message.success('处理成功');
    dealModalVisible.value = false;
    loadData();
  } catch {
    message.error('处理失败');
  }
}

// 修改加载数据方法
async function loadData() {
  try {
    gridApi.setLoading(true);
    const params = {
      current_page: currentPage.value,
      ...searchForm.value,
    };
    const data = await getWithdrawListApi(params);

    if (!Array.isArray(data) || data.length === 0) {
      message.error('获取数据格式错误');
      tableData.value = [];
      return;
    }

    // 从返回数据的第一条记录中获取总页数
    totalPage.value = data[0]?.total_page || 1;
    tableData.value = data;

    gridApi.setGridOptions({
      data: tableData.value,
      pagerConfig: {
        total: totalPage.value * 10,
        currentPage: currentPage.value,
        pageSize: 10,
      },
    });
  } catch {
    tableData.value = [];
    totalPage.value = 1;
  } finally {
    gridApi.setLoading(false);
  }
}

// 搜索方法
function handleSearch() {
  currentPage.value = 1; // 搜索时重置到第一页
  loadData();
}

// 重置搜索条件
function handleReset() {
  searchForm.value = {
    username: '',
    status: -1,
  };
  currentPage.value = 1; // 重置时回到第一页
  loadData();
}

onMounted(() => {
  loadData();
});

// 表格显示控制
const showBorder = gridApi.useStore((state) => state.gridOptions?.border);
const showStripe = gridApi.useStore((state) => state.gridOptions?.stripe);

function changeBorder() {
  gridApi.setGridOptions({
    border: !showBorder.value,
  });
}

function changeStripe() {
  gridApi.setGridOptions({
    stripe: !showStripe.value,
  });
}

// 在 script 部分添加以下接口定义
interface VipUserDetail {
  username: string;
  vip_price: number;
  vip_money_ref: number;
}

interface WithdrawDetail {
  vip_users_direct: VipUserDetail[];
  vip_users_indirect: VipUserDetail[];
}

// 添加新的响应式变量
const detailModalVisible = ref(false);
const currentDetail = ref<WithdrawDetail | null>(null);

// 添加显示详情的方法
function showDetail(row: WithdrawInfo) {
  try {
    const detail = JSON.parse(row.detail) as WithdrawDetail;
    currentDetail.value = detail;
    detailModalVisible.value = true;
  } catch (e) {
    message.error('解析详情数据失败');
  }
}

// 在 script 部分添加计算属性来统计金额
const directTotalAmount = computed(() => {
  if (!currentDetail.value?.vip_users_direct) return 0;
  return currentDetail.value.vip_users_direct.reduce((sum, user) => sum + user.vip_money_ref, 0);
});

const indirectTotalAmount = computed(() => {
  if (!currentDetail.value?.vip_users_indirect) return 0;
  return currentDetail.value.vip_users_indirect.reduce((sum, user) => sum + user.vip_money_ref, 0);
});
</script>

<template>
  <div class="p-4">
    <!-- 搜索表单 -->
    <Form class="mb-4" layout="inline">
      <Form.Item label="用户名">
        <Input
          v-model:value="searchForm.username"
          allow-clear
          placeholder="请输入用户名"
        />
      </Form.Item>
      <Form.Item label="状态">
        <Select
          v-model:value="searchForm.status"
          :options="statusOptions"
          style="width: 120px"
        />
      </Form.Item>
      <Form.Item>
        <Button class="mr-2" type="primary" @click="handleSearch">搜索</Button>
        <Button @click="handleReset">重置</Button>
      </Form.Item>
    </Form>

    <div class="vp-raw w-full">
      <Grid ref="gridRef">
        <template #toolbar-tools>
          <Button class="mr-2" type="primary" @click="changeBorder">
            {{ showBorder ? '隐藏' : '显示' }}边框
          </Button>
          <Button class="mr-2" type="primary" @click="changeStripe">
            {{ showStripe ? '隐藏' : '显示' }}斑马纹
          </Button>
        </template>

        <!-- 添加操作列的插槽 -->
        <template #operate="{ row }">
          <Button
            v-if="row.apply_status === '待处理'"
            type="primary"
            @click="handleDeal(row)"
          >
            处理
          </Button>
        </template>

        <!-- 添加详情按钮的插槽 -->
        <template #detail="{ row }">
          <Button type="link" @click="showDetail(row)">查看详情</Button>
        </template>
      </Grid>
    </div>

    <!-- 处理提款弹窗 -->
    <Modal
      v-model:visible="dealModalVisible"
      title="处理提款"
      @ok="confirmDeal"
    >
      <Form layout="vertical">
        <Form.Item label="备注">
          <Input v-model:value="dealComment" placeholder="请输入处理备注" />
        </Form.Item>
      </Form>
    </Modal>

    <!-- 详情弹窗 -->
    <Modal
      v-model:visible="detailModalVisible"
      title="提现详情"
      width="800px"
      :footer="null"
    >
      <div v-if="currentDetail" class="detail-container">
        <div class="flex gap-4">
          <!-- 直接推广用户卡片 -->
          <div class="flex-1 bg-blue-50 rounded-lg p-4">
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-lg font-bold text-blue-700">直接推广VIP用户</h3>
              <span class="text-blue-600">
                总返佣: ¥{{ directTotalAmount }}
              </span>
            </div>
            <div class="max-h-[400px] overflow-y-auto">
              <div v-if="currentDetail.vip_users_direct.length > 0">
                <div 
                  v-for="(user, index) in currentDetail.vip_users_direct" 
                  :key="index" 
                  class="bg-white rounded p-3 mb-2 shadow-sm"
                >
                  <div class="flex justify-between items-center">
                    <span class="font-medium">{{ user.username }}</span>
                    <span class="text-blue-500">+¥{{ user.vip_money_ref }}</span>
                  </div>
                  <div class="text-gray-500 text-sm mt-1">
                    VIP价格: ¥{{ user.vip_price }}
                  </div>
                </div>
              </div>
              <div v-else class="text-gray-500 text-center py-4">
                暂无直接推广用户
              </div>
            </div>
          </div>

          <!-- 间接推广用户卡片 -->
          <div class="flex-1 bg-green-50 rounded-lg p-4">
            <div class="flex justify-between items-center mb-4">
              <h3 class="text-lg font-bold text-green-700">间接推广VIP用户</h3>
              <span class="text-green-600">
                总返佣: ¥{{ indirectTotalAmount }}
              </span>
            </div>
            <div class="max-h-[400px] overflow-y-auto">
              <div v-if="currentDetail.vip_users_indirect.length > 0">
                <div 
                  v-for="(user, index) in currentDetail.vip_users_indirect" 
                  :key="index" 
                  class="bg-white rounded p-3 mb-2 shadow-sm"
                >
                  <div class="flex justify-between items-center">
                    <span class="font-medium">{{ user.username }}</span>
                    <span class="text-green-500">+¥{{ user.vip_money_ref }}</span>
                  </div>
                  <div class="text-gray-500 text-sm mt-1">
                    VIP价格: ¥{{ user.vip_price }}
                  </div>
                </div>
              </div>
              <div v-else class="text-gray-500 text-center py-4">
                暂无间接推广用户
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>
